package queue;

import java.util.Arrays;

public class LoopDeque<E> implements Deque<E> {
    private E[] data;
    private int front, tail;
    private int size;

    public LoopDeque(int capacity) {
        data = (E[]) new Object[capacity];
        front = 0;
        tail = 0;
        size = 0;
    }

    public int getCapacity() {
        return data.length;
    }

    @Override
    public void addFront(E e) {
        if (getSize() == getCapacity()) resize(getCapacity() * 2);
        //首先要确定添加新元素的索引位置
        //这个位置是front-1的位置
        //如果front==0，新的位置是data.length-1的位置
        data[front] = e;
        front = front == 0 ? getCapacity() - 1 : front - 1;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % getCapacity()];
        }
        front = 0;
        tail = size;
        data = newData;
    }

    /**
     * addFront 是新的方法
     *
     * @param e
     */
    @Override
    public void addLast(E e) {
        if (getSize() == getCapacity()) resize(getCapacity() * 2);
        data[tail] = e;
        tail = (tail + 1) % getCapacity();
        size++;
    }

    @Override
    public E removeFront() {
        if (isEmpty()) throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        E result = data[front];
        data[front] = null;
        front = (front + 1) % getCapacity();
        size--;
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0) resize(getCapacity() / 2);
        return result;
    }

    @Override
    public E removeLast() {
        if (isEmpty()) throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        E result = data[tail];
        data[tail] = null;
        tail = tail == 0 ? getCapacity() - 1 : tail - 1;
        size--;
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0) resize(getCapacity() / 2);
        return null;
    }


    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E getFront() {
        return data[front];
    }

    @Override
    public E getLast() {
        return data[tail];
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("Queue:size=%d, capacity=%d\n"), getSize(), getCapacity());
        res.append("front [");
        for (int i = 0; i < size; i++) {
            res.append(data[(i + front) % getCapacity()]);
            if (i != size - 1) {
                res.append(", ");
            }
        }
        res.append("] tail");
        return res.toString();
    }
}
